<?php

class Talktangle_Model_DbTable_Promotions extends Engine_Db_Table
{
    protected $_rowClass = 'Talktangle_Model_Promotion';
    
    /**
   * @const SET IMAGE WIDTH
   */
  const IMAGE_WIDTH = 720;
  /**
   * @const SET IMAGE HIGHT
   */
  const IMAGE_HEIGHT = 720;
  /**
   * @const SET THUMB IMAGE WIDTH
   */
  const THUMB_WIDTH = 140;
  /**
   * @const SET THUMB IMAGE HIGHT
   */
  const THUMB_HEIGHT = 160;
  public function uploadPhoto($params,$file){
    if ($file instanceof Storage_Model_File) {
      $params['file_id'] = $file->getIdentity();
    } 
    else 
    {
      //Get image info and resize
      $name = basename($file['tmp_name']);
      $path = dirname($file['tmp_name']);
      $extension = ltrim(strrchr($file['name'], '.'), '.');

       
      $mainName = $path . '/m_' . $name . '.' . $extension;
      $thumbName = $path . '/t_' . $name . '.' . $extension;
        
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::IMAGE_WIDTH, self::IMAGE_HEIGHT)
              ->write($mainName)
              ->destroy();
     
        
      $image = Engine_Image::factory();
      $image->open($file['tmp_name'])
              ->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
              ->write($thumbName)
              ->destroy();
      
      $thumbW = $image->getWidth();
      $thumbH = $image->getHeight();
        
      //Store photos
      $photo_params = array(
          'parent_id' => 0,
          'parent_type' => 'talktangle_promotion',
      );
      
     
      
      $photoFile = Engine_Api::_()->storage()->create($mainName, $photo_params);
      $photoFile->save();
      
      $thumbFile = Engine_Api::_()->storage()->create($thumbName, $photo_params);
      $thumbFile->save();
      $photoFile->bridge($thumbFile, 'thumb.normal');
      
      //Storage full size image.
      if (Engine_Api::_()->getApi('settings', 'core')->getSetting('photo.fullsize.storage', 0)) {
          $fullsizeName = $path . '/o_' . $name . '.' . $extension;
          $image = Engine_Image::factory();
          $image->open($file['tmp_name'])
                  //->resize(self::THUMB_WIDTH, self::THUMB_HEIGHT)
                  ->write($fullsizeName)
                  ->destroy();
          $fullsizeFile = Engine_Api::_()->storage()->create($fullsizeName, $photo_params);
          $fullsizeFile->save();
          $photoFile->bridge($fullsizeFile, 'fullsize.normal');
          @unlink($fullsizeName);          
          //$fullsizeFile->width = $fullW;
          //$fullsizeFile->height = $fullH;
          
      }
    
      //Remove temp files
      @unlink($mainName);
      @unlink($thumbName);
        
      return $photoFile;

      
    } 
  }
  
  public function setPhoto($photo)
  { 
    $viewer = Engine_Api::_()->user()->getViewer();
    if( $photo instanceof Zend_Form_Element_File ) {
      $file = $photo->getFileName();
      $fileName = $file;
    } else if( $photo instanceof Storage_Model_File ) {
      $file = $photo->temporary();
      $fileName = $photo->name;
    } else if( $photo instanceof Core_Model_Item_Abstract && !empty($photo->file_id) ) {
      $tmpRow = Engine_Api::_()->getItem('storage_file', $photo->file_id);
      $file = $tmpRow->temporary();
      $fileName = $tmpRow->name;
    } else if( is_array($photo) && !empty($photo['tmp_name']) ) {
      $file = $photo['tmp_name'];
      $fileName = $photo['name'];
    } else if( is_string($photo) && file_exists($photo) ) {
      $file = $photo;
      $fileName = $photo;
    } else {
      throw new User_Model_Exception('invalid argument passed to setPhoto');
    }

    if( !$fileName ) {
      $fileName = $file;
    }

    $name = basename($file);
    $extension = ltrim(strrchr($fileName, '.'), '.');
    $base = rtrim(substr(basename($fileName), 0, strrpos(basename($fileName), '.')), '.');
    $path = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'temporary';
    $params = array(
      'parent_type' => 'talktangle_promotion',
      'parent_id' => '0',
      'user_id' => $viewer->getIdentity(),
      'name' => $fileName,
    );

    // Save
    $filesTable = Engine_Api::_()->getDbtable('files', 'storage');

    // Resize image (main)
    $mainPath = $path . DIRECTORY_SEPARATOR . $base . '_m.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file)
      ->resize(720, 720)
      ->write($mainPath)
      ->destroy();
    
    // Resize image (normal)
    $normalPath = $path . DIRECTORY_SEPARATOR . $base . '_in.' . $extension;
    $image = Engine_Image::factory();
    $image->open($file)
      ->resize(200,400)
      ->write($normalPath)
      ->destroy();
    
    // Store
    try {
      $iMain = $filesTable->createFile($mainPath, $params);
      $iIconNormal = $filesTable->createFile($normalPath, $params);
      
      $iMain->bridge($iIconNormal, 'thumb.normal');
    } catch( Exception $e ) {
      // Remove temp files
      @unlink($mainPath);
      @unlink($normalPath);
      // Throw
      if( $e->getCode() == Storage_Model_DbTable_Files::SPACE_LIMIT_REACHED_CODE ) {
        throw new Ialbum_Model_Exception($e->getMessage(), $e->getCode());
      } else {
        throw $e;
      }
    }
    
    // Remove temp files
    @unlink($mainPath);
    @unlink($normalPath);

    // Update row
//    $this->modified_date = date('Y-m-d H:i:s');
//    $this->file_id = $iMain->file_id;
//    $this->save();

    // Delete the old file?
    if( !empty($tmpRow) ) {
      $tmpRow->delete();
    }

    return $iMain->file_id;
  }   
}